package com.erp.framework.manager.factory;

import com.erp.framework.domain.SysOperaLog;
import com.erp.framework.domain.SysUserOnline;
import com.erp.framework.service.ISysOperaLogService;
import com.erp.framework.service.ISysUserOnlineService;
import com.erp.framework.shiro.session.OnlineSession;
import com.erp.framework.util.AddressUtils;
import com.erp.framework.util.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author liuhulu
 */
public class AsyncFactory {

    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 同步session到数据库
     *
     * @param session 在线用户会话
     * @return 任务task
     */
    public static TimerTask syncSessionToDb(final OnlineSession session) {
        return new TimerTask() {
            @Override
            public void run() {
                SysUserOnline online = new SysUserOnline();
                online.setSessionId(String.valueOf(session.getId()));
                online.setDeptName(session.getDeptName());
                online.setLoginName(session.getUserName());
                online.setStartTimestamp(session.getStartTimestamp());
                online.setLastAccessTime(session.getLastAccessTime());
                online.setExpireTime(session.getTimeout());
                online.setIpaddr(session.getHost());
                online.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost()));
                online.setBrowser(session.getBrowser());
                online.setOs(session.getOs());
                online.setStatus(session.getStatus());
                SpringUtils.getBean(ISysUserOnlineService.class).saveOnline(online);

            }
        };
    }

    /**
     * 操作日志记录
     *
     * @return 任务task
     */
    public static TimerTask recordOpera(final SysOperaLog operaLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operaLog.setOperaLocation(AddressUtils.getRealAddressByIP(operaLog.getOperaIp()));
                SpringUtils.getBean(ISysOperaLogService.class).insert(operaLog);
            }
        };
    }

}
